package com.zhuang.rabbitmq.topics;


import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Classname Producer
 * @Description 生产者主题模式
 * @Date 2021/4/15 15:38
 * @Created by dell
 */

public class Producer {
    public static void main(String[] args) {
        // 创建连接工程
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.152.130");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        connectionFactory.setVirtualHost("/");
        //创建Connection
        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            //通过连接获得通道Channel
            channel = connection.createChannel();
            //通过交换机创建 声明队列 绑定关系 路由key 发送消息 和接收消息

        //    String queueName = "queue1";

            String message = "hello topics !!!";
            /*
            队列名称
            是否要持久化
            排他性
            是否自动删除
            携带附属参数
             */
            //准备交换机
            String exchangeName="topic_exchange";

            //定义路由Key
            String routeKey="com.order.user.test.xxxx";
            //定义交换机类型
            String type="topic";
          //  channel.queueDeclare(queueName, false, false, false, null);

            //发送消息给队列
            channel.basicPublish(exchangeName, routeKey, null, message.getBytes());

            System.out.println("消息发送成功");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        } finally {
            if (channel != null && channel.isOpen()) {
                try {
                    connection.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
